from urllib.request import urlopen
from html.parser import HTMLParser
import sys
import re
import pokeparser
import abilityinfo

class ability(HTMLParser):
	def __init__(self):
		super().__init__()
		self.in_table = self.in_tr = self.in_td = self.in_ja = self.in_en = self.in_des = self.in_num = self.in_hide = False
		self.url = self.cname = self.jname = self.ename = self.des = ''
		self.aid = self.num = self.hide = 0
		self.p = pokeparser.pokeparser()
		self.text = self.p.gettext(self.p.ability())
		self.f = open('text/ability.txt','a+',encoding='utf-8')
		self.u = open('url/abilityurl.txt','a+',encoding='utf-8')
		with open('text/ability.txt',encoding='utf-8') as f:
			self.startcount = len(f.readlines())
		self.count = 0
	def handle_starttag(self, tag, attrs):
		attrs = dict(attrs)
		title = attrs.get('title','')
		lang = attrs.get('lang','')
		m = re.search('(.+?)（特性）',title)
		if tag == 'tbody':
			self.in_table = True
		elif tag == 'tr' and self.in_table:
			self.in_tr = True
		elif tag == 'td' and self.in_tr:
			self.in_td = True
			if lang == 'ja':
				self.in_ja = True
			elif lang == 'en':
				self.in_en = True
		# 获得特性中文名：
		elif tag == 'a' and self.in_td and m:
			self.cname = m.group(1)
			self.url = self.p.combine(attrs.get('href',''))
	def handle_data(self, data):
		data = str(data).strip(' \n')
		if re.search('^[0-9]*$',data) and self.in_td:
			# 获得特性id：
			if self.aid == 0 and data != '':
				self.aid = int(data)
			elif self.des != '':
				if data == '':
					data = 0
				# 获得拥有普通特性的宝可梦数量：
				if self.in_num:
					self.num = int(data)
					self.in_num = False
					self.in_hide = True
				# 获得拥有隐藏特性的宝可梦数量：
				elif self.in_hide:
					self.hide = int(data)
					self.in_hide = False
					self.count += 1
					self.finish()
		elif self.cname != '' and data != '':
			# 获得特性日文名：
			if self.in_ja:
				self.jname = data
				self.in_ja = False
			# 获得特性英文名：
			elif self.in_en:
				self.ename = data
				self.in_en = False
				self.in_des = True
			# 获得特性描述：
			elif self.in_des:
				self.des = data
				self.in_des = False
				self.in_num = True
	def finish(self):
		if self.count > self.startcount:
			p = abilityinfo.abilityinfo(self.url)
			p.feed(p.text)
			p.close()
			info = [self.aid,self.cname,self.jname,self.ename,self.des,self.num,self.hide,p.info,p.effect]
			temp = sys.stdout
			sys.stdout = self.f
			print(info)
			self.f.flush()
			sys.stdout = self.u
			print(self.url)
			self.u.flush()
			sys.stdout = temp
			print(info)
		self.url = self.cname = self.jname = self.ename = self.des = ''
		self.aid = self.num = self.hide = 0

	def handle_endtag(self, tag):
		if tag == 'tbody':
			self.in_table = False
		elif tag == 'tr':
			self.in_tr = False
		elif tag == 'td':
			self.in_td = False

def writetxt():
	a = ability()
	a.feed(a.text)
	a.close()

if __name__ == "__main__":
	writetxt()
